#!/bin/bash
set -u

CONTENTS_DIR="$(cd "$(dirname "$0")/.." && pwd)"
RESOURCES="$CONTENTS_DIR/Resources"
SUPPORT="$HOME/Library/Application Support/V5 Device Bridge"
APP_DIR="$SUPPORT/app"
DATA_DIR="$SUPPORT/data"
TOOLS_DIR="$SUPPORT/tools"
VENV_DIR="$SUPPORT/venv"
LOG_DIR="$SUPPORT/logs"
INSTALL_LOG="$LOG_DIR/install.log"
LAUNCH_AGENT="$HOME/Library/LaunchAgents/com.sgsystems.v5devicebridge.plist"
START_SCRIPT="$SUPPORT/start-service.sh"
STATUS_URL="http://127.0.0.1:8765/api/status"
BRIDGE_URL="http://127.0.0.1:8765"

mkdir -p "$APP_DIR" "$DATA_DIR" "$TOOLS_DIR" "$LOG_DIR" "$HOME/Library/LaunchAgents"
exec >>"$INSTALL_LOG" 2>&1
printf '\n[%s] V5 Device Bridge launch\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"

if /usr/bin/curl -fsS --max-time 1 "$STATUS_URL" >/dev/null 2>&1; then
  /usr/bin/open "$BRIDGE_URL"
  exit 0
fi

/usr/bin/open "$RESOURCES/splash.html"

fail() {
  message="$1"
  echo "ERROR: $message"
  /usr/bin/osascript -e "display alert \"Device Bridge could not start\" message \"$message\" as critical buttons {\"Close\"} default button \"Close\"" >/dev/null 2>&1 || true
  exit 1
}

# Copy the signed application payload to stable per-user storage while preserving data separately.
/usr/bin/ditto "$RESOURCES/app" "$APP_DIR" || fail "The application files could not be installed."

ARCH="$(/usr/bin/uname -m)"
UV="$TOOLS_DIR/uv"
UV_VERSION="0.11.32"
if [ "$ARCH" = "arm64" ]; then
  UV_ARCHIVE="uv-aarch64-apple-darwin.tar.gz"
  UV_SHA="ed336d0ba49db8ef89b2b41fffa372ce63bd032f22a56f001c265891aec32829"
elif [ "$ARCH" = "x86_64" ]; then
  UV_ARCHIVE="uv-x86_64-apple-darwin.tar.gz"
  UV_SHA="77f5ca26c0de20e992a3677a174fe1121ee25c36f9b1434a863f75bf077a05eb"
else
  fail "This Mac processor is not supported yet."
fi

if [ ! -x "$UV" ]; then
  TMP_ROOT="$(/usr/bin/mktemp -d -t v5bridge)" || fail "A temporary installation folder could not be created."
  ARCHIVE="$TMP_ROOT/$UV_ARCHIVE"
  URL="https://releases.astral.sh/github/uv/releases/download/$UV_VERSION/$UV_ARCHIVE"
  /usr/bin/curl --proto '=https' --tlsv1.2 -L --fail --silent --show-error "$URL" -o "$ARCHIVE" || fail "The private runtime could not be downloaded. Check the internet connection and try again."
  ACTUAL_SHA="$(/usr/bin/shasum -a 256 "$ARCHIVE" | /usr/bin/awk '{print $1}')"
  [ "$ACTUAL_SHA" = "$UV_SHA" ] || fail "The downloaded runtime failed its integrity check."
  /usr/bin/tar -xzf "$ARCHIVE" -C "$TMP_ROOT" || fail "The private runtime could not be unpacked."
  FOUND_UV="$(/usr/bin/find "$TMP_ROOT" -type f -name uv -perm +111 | /usr/bin/head -n 1)"
  [ -n "$FOUND_UV" ] || fail "The private runtime package did not contain the expected launcher."
  /bin/cp "$FOUND_UV" "$UV" || fail "The private runtime could not be installed."
  /bin/chmod 700 "$UV"
  /bin/rm -rf "$TMP_ROOT"
fi

export UV_CACHE_DIR="$SUPPORT/cache"
export UV_PYTHON_INSTALL_DIR="$SUPPORT/python"

if [ ! -x "$VENV_DIR/bin/python" ]; then
  "$UV" venv --python 3.12 "$VENV_DIR" || fail "Python could not be prepared for Device Bridge."
fi

"$UV" pip install --quiet --python "$VENV_DIR/bin/python" -r "$APP_DIR/requirements-macos.txt" || fail "Required Device Bridge components could not be installed."

cat > "$START_SCRIPT" <<EOF
#!/bin/bash
export V5_BRIDGE_DATA_DIR="$DATA_DIR"
export V5_BRIDGE_AUTO_OPEN=0
cd "$APP_DIR"
exec "$VENV_DIR/bin/python" "$APP_DIR/run.py"
EOF
/bin/chmod 700 "$START_SCRIPT"

cat > "$LAUNCH_AGENT" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>Label</key><string>com.sgsystems.v5devicebridge</string>
<key>ProgramArguments</key><array><string>/bin/bash</string><string>$START_SCRIPT</string></array>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><true/>
<key>ProcessType</key><string>Background</string>
<key>StandardOutPath</key><string>$LOG_DIR/service-output.log</string>
<key>StandardErrorPath</key><string>$LOG_DIR/service-error.log</string>
<key>WorkingDirectory</key><string>$APP_DIR</string>
</dict></plist>
EOF

UID_VALUE="$(/usr/bin/id -u)"
/bin/launchctl bootout "gui/$UID_VALUE/com.sgsystems.v5devicebridge" >/dev/null 2>&1 || true
/bin/launchctl bootstrap "gui/$UID_VALUE" "$LAUNCH_AGENT" >/dev/null 2>&1 || {
  /bin/launchctl unload "$LAUNCH_AGENT" >/dev/null 2>&1 || true
  /bin/launchctl load "$LAUNCH_AGENT" >/dev/null 2>&1 || fail "The background bridge service could not be registered."
}
/bin/launchctl kickstart -k "gui/$UID_VALUE/com.sgsystems.v5devicebridge" >/dev/null 2>&1 || true

for _ in $(/usr/bin/seq 1 90); do
  if /usr/bin/curl -fsS --max-time 1 "$STATUS_URL" >/dev/null 2>&1; then
    /usr/bin/open "$BRIDGE_URL"
    exit 0
  fi
  /bin/sleep 1
done

fail "The local service did not become ready. Restart the Mac and open Device Bridge again."
